package com.sdtv.basemodule.rx.errorhandler;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.rx.errorhandler
 * @ClassName: RetryWithDelay
 * @Description: java类作用描述
 * @Author: 小郭同学
 * @CreateDate: 2019-07-03 10:11
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class RetryWithDelay implements Function<Observable<Throwable>, ObservableSource<?>> {


    // 重连的最大次数
    private int maxRetryNum;
    //重连时间
    private int retryDelay;
    // 已经重连的数量
    private int retryCount;

    public RetryWithDelay(int maxRetryNum, int retryDelay) {
        this.maxRetryNum = maxRetryNum;
        this.retryDelay = retryDelay;
    }

    /**
     * 执行重连事件 或者返回 失败消息
     *
     * @param throwableObservable
     * @return
     */
    @Override
    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {
        return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(Throwable throwable) throws Exception {
                if (retryCount < maxRetryNum) {
                    retryCount++;
                    return Observable.timer(retryDelay, TimeUnit.SECONDS);
                }
                return Observable.error(throwable);
            }
        });
    }
}
